/*
 * @Author: ZhanXie
 * @Date: 2019-11-26 11:38:58
 * @LastEditors: ZhanXie
 * @LastEditTime: 2019-12-03 18:31:32
 * @Description: blog 控制层
 * @FilePath: /node-demo/blog-origin/src/controller/blog.js
 */
const xss = require('xss')
const { exec, escape } = require('../db/mysql')

const getList = (author, keyword) => {
  
  let sql = `select * from blogs where 1=1 `
  if (author) {
    author = escape(author)
    sql += `and author=${author} `
  }

  if (keyword) {
    keyword = escape(`%${keyword}%`)
    sql += `and title like ${keyword} `
  }
  sql += `order by createtime desc;`
  // 返回 promise
  return exec(sql)
}

const getDetail = (id) => {
  const sql = `select * from blogs where id=${id};`
  return exec(sql).then(rows => rows[0])
}

const newBlog = (blogData = {}) => {
  // blogData 是一个博客对象, 包含 title content 属性
  const title = xss(escape(blogData.title)) || ''
  const content = xss(escape(blogData.content)) || ''
  const author = xss(escape(blogData.author)) || ''
  const createtime = Date.now()

  const sql = `insert into blogs(title, content, author, createtime) value (${title}, ${content}, ${author}, ${createtime});`
  return exec(sql).then(insertData => {
    return {
      id: insertData.insertId
    }
  })
}

const updateBlog = (id, blogData = {}) => {
  // id 就是要更新博客的id
  // blogData 是一个博客对象, 包含 title content 属性
  const title = xss(escape(blogData.title)) || ''
  const content = xss(escape(blogData.content)) || ''

  const sql = `update blogs set title=${title}, content=${content} where id=${id};`
  return exec(sql).then(updateData => {
    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}

const delBlog = (id, author) => {
  author = escape(author)
  const sql = `delete from blogs where id=${id} and author=${author};` // 防止越权操作
  return exec(sql).then(delData => {
    if (delData.affectedRows > 0) {
      return true
    }
    return false
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}